package com.xoa.service.trainingPlanRecord;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.trainingPlan.EduTrainingPlanMapper;
import com.xoa.dao.trainingPlanRecord.EduTrainingRecordMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.department.Department;
import com.xoa.model.trainingPlan.EduTrainingPlan;
import com.xoa.model.trainingPlanRecord.EduTrainingRecordWithBLOBs;
import com.xoa.model.users.Users;
import com.xoa.util.AjaxJson;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

/**
 * 创建作者:   高亚峰
 * 创建日期:   2017/9/11 17:06
 * 类介绍  :   培训记录实现类
 * 构造参数:
 */
@Service
public class EduTrainingRecordService {

    @Resource
    private EduTrainingRecordMapper eduTrainingRecordMapper;
    @Autowired
    private DepartmentMapper eduDepartmentMapper;
    @Autowired
    private EduTrainingPlanMapper eduTrainingPlanMapper;
    @Autowired
    UsersMapper usersMapper;
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/11 17:46
     * 类介绍  :   培训记录添加
     * 构造参数:   EduTrainingRecordWithBLOBs
     */
    public AjaxJson addEduTrainPlainRecord(HttpServletRequest request, EduTrainingRecordWithBLOBs eduTrainingRecordWithBLOBs){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setFlag(false);
        try {
            //从session中获取当前登录人的信息
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            eduTrainingRecordWithBLOBs.setCreateUserId(users.getUserId());
            eduTrainingRecordWithBLOBs.setCreateDeptId(users.getDeptId());
            Map<String, Object> map = new HashMap<String, Object>();

            eduTrainingRecordMapper.insertSelective(eduTrainingRecordWithBLOBs);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/11 17:46
     * 类介绍  :   培训记录编辑
     * 构造参数:   EduTrainingRecordWithBLOBs
     */
    public AjaxJson editRecord(HttpServletRequest request,EduTrainingRecordWithBLOBs eduTrainingRecordWithBLOBs){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setFlag(false);
        try {
            int i = eduTrainingRecordMapper.updateByPrimaryKeySelective(eduTrainingRecordWithBLOBs);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/11 17:46
     * 类介绍  :   培训记录删除
     * 构造参数:   EduTrainingRecordWithBLOBs
     */
    public AjaxJson deleteRecordById(HttpServletRequest request,Integer recordId){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setFlag(false);
        try {
            int i = eduTrainingRecordMapper.deleteByPrimaryKey(recordId);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/11 17:46
     * 类介绍  :   培训记录查询详情
     * 构造参数:   recordId
     */
    public AjaxJson getdetail(HttpServletRequest request,Integer recordId){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setFlag(false);
        try {
            EduTrainingRecordWithBLOBs eduTrainingRecordWithBLOBs = eduTrainingRecordMapper.selectByPrimaryKey(recordId);
            if(eduTrainingRecordWithBLOBs.getCreateUserId()!=null){
                Users byuserId = usersMapper.getUserId(eduTrainingRecordWithBLOBs.getCreateUserId());
                eduTrainingRecordWithBLOBs.setCreateUserName(byuserId.getUserName());
            }
            if(eduTrainingRecordWithBLOBs.getCreateDeptId()!=null){
                Department eduDepartmentWithBLOBs = eduDepartmentMapper.getDeptById(Integer.valueOf(eduTrainingRecordWithBLOBs.getCreateDeptId()));
                eduTrainingRecordWithBLOBs.setCreateDeptName(eduDepartmentWithBLOBs.getDeptName());
            }
            StringBuffer sb =new StringBuffer();
            if(eduTrainingRecordWithBLOBs.getStaffUserId()!=null){
                String staffUserId = eduTrainingRecordWithBLOBs.getStaffUserId();
                String[] split = staffUserId.split(",");
                for(String s:split){
                    Users byuserId = usersMapper.getUserId(s);
                    sb.append(byuserId.getUserName()+",");
                }
            }
            eduTrainingRecordWithBLOBs.setStaffUserName(sb.toString());
            ajaxJson.setObj(eduTrainingRecordWithBLOBs);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/11 17:46
     * 类介绍  :   培训记录列表展示接口
     * 构造参数:   分页参数
     */
    public AjaxJson getAll(HttpServletRequest request,Integer page, Integer pageSize, Boolean useFlag,String staffUserId){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setFlag(false);
        try {
            //分页处理
            PageParams pageParams = new PageParams();
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("staffUserId",staffUserId);
            //查询所有数据
            List<EduTrainingRecordWithBLOBs> all = eduTrainingRecordMapper.getAll(map);

            for(EduTrainingRecordWithBLOBs eduTrainingRecordWithBLOBs:all){
                StringBuffer sb =new StringBuffer();
                if(eduTrainingRecordWithBLOBs.getStaffUserId()!=null){
                    String staffUserIds = eduTrainingRecordWithBLOBs.getStaffUserId();
                    String[] split = staffUserIds.split(",");
                   for(String s:split){
                       Users byuserId = usersMapper.getUserId(s);
                       if(byuserId!=null){
                           sb.append(byuserId.getUserName()+",");
                       }
                   }
                }
                eduTrainingRecordWithBLOBs.setStaffUserName(sb.toString());
            }
            int count = eduTrainingRecordMapper.getCount();
            ajaxJson.setTotleNum(count);
            ajaxJson.setObj(all);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/11 17:53
     * 类介绍  :   培训记录查询
     * 构造参数:   EduTrainingRecordWithBLOBs
     */
    public AjaxJson queryRecord(EduTrainingRecordWithBLOBs eduTrainingRecordWithBLOBs,String export,HttpServletRequest request,HttpServletResponse response){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setFlag(false);
        if(export==null){
            export="0";
        }
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("eduTrainingRecordWithBLOBs",eduTrainingRecordWithBLOBs);
            List<EduTrainingRecordWithBLOBs> all = eduTrainingRecordMapper.queryRecord(map);
            for(EduTrainingRecordWithBLOBs eduTrainingRecordWithBLOBs1:all){
             if(eduTrainingRecordWithBLOBs1.getCreateUserId()!=null){
                 Users byuserId = usersMapper.getUserId(eduTrainingRecordWithBLOBs1.getCreateUserId());
                 eduTrainingRecordWithBLOBs1.setCreateUserName(byuserId.getUserName());
             }
            if(eduTrainingRecordWithBLOBs1.getCreateDeptId()!=null){
                Department eduDepartmentWithBLOBs2 = eduDepartmentMapper.getDeptById(Integer.valueOf(eduTrainingRecordWithBLOBs1.getCreateDeptId()));
                eduTrainingRecordWithBLOBs1.setCreateDeptName(eduDepartmentWithBLOBs2.getDeptName());
            }
                StringBuffer sb =new StringBuffer();
                if(eduTrainingRecordWithBLOBs1.getStaffUserId()!=null){
                    String staffUserId = eduTrainingRecordWithBLOBs1.getStaffUserId();
                    String[] split = staffUserId.split(",");
                    for(String s:split){
                        Users byuserId = usersMapper.getUserId(s);
                        if(byuserId!=null){
                            sb.append(byuserId.getUserName()+",");
                        }
                    }
                }
                eduTrainingRecordWithBLOBs1.setStaffUserName(sb.toString());
            }
            ajaxJson.setObj(all);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
            if(export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("培训记录导出信息表", 9);
                String[] secondTitles = {"Id", "创建者用户名", "创建者部门","培训人员","培训计划编号", "培训计划名称", "培训机构名称", "培训费用", "出勤情况"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"recordId","createUserName", "createDeptName","staffUserName","tPlanNo", "tPlanName", "tInstitutionName", "trainningCost", "dutySituation"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, all, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "培训记录导出信息表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }


        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017/9/11 17:46
     * 类介绍  :   批量删除培训记录
     * 构造参数:   EduTrainingRecordWithBLOBs
     */
    public AjaxJson deleteByIds(String []recordIds){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setFlag(false);
        try {
           eduTrainingRecordMapper.deleteByIds(recordIds);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }
    /**
     * 创建作者:   陈玲
     * 创建日期:   2018/7/27 17:46
     * 类介绍  :   查询培训计划的新建培训名称
     * 构造参数:
     */
    public AjaxJson FindAllsPlane(){
        AjaxJson ajaxJson =new AjaxJson();
        ajaxJson.setFlag(false);
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            //查询所有数据
            List<EduTrainingRecordWithBLOBs> all = eduTrainingRecordMapper.getAll(map);
            List<EduTrainingPlan> allPlan = eduTrainingPlanMapper.getAllPlanTrue();
            String plan =null;
            String planName =null;
//            List<String> array=new ArrayList();
//            List<String> arras=new ArrayList();
            List<EduTrainingRecordWithBLOBs> array=new ArrayList();
            List<EduTrainingPlan> arras=new ArrayList();
            EduTrainingRecordWithBLOBs record=null;
            for( EduTrainingRecordWithBLOBs a:all) {
                record=new EduTrainingRecordWithBLOBs();
                record.settPlanName(a.gettPlanName());
                record.settPlanNo(a.gettPlanNo());
                array.add(record);
//                array.add (a.gettPlanNo());
            }
            EduTrainingPlan tPlan=null;
            for (EduTrainingPlan al : allPlan) {
                tPlan=new EduTrainingPlan();
                tPlan.setPlanName(al.getPlanName());
                tPlan.setPlanNo(al.getPlanNo());
                arras.add(tPlan);
//                arras.add ( al.getPlanNo() );
                }
            Collection exists=new ArrayList<EduTrainingPlan>(arras);
            exists.removeAll(array);
            ajaxJson.setObj (exists);
            ajaxJson.setMsg("ok");
            ajaxJson.setFlag(true);
        } catch (Exception e) {
            ajaxJson.setMsg(e.getMessage());
            ajaxJson.setFlag(false);
            e.printStackTrace();
        }
        return ajaxJson;
    }
    public ToJson<EduTrainingRecordWithBLOBs> getByStaffName(String staffName, Integer page, Integer pageSize, boolean useFlag){
        ToJson<EduTrainingRecordWithBLOBs> json=new ToJson<EduTrainingRecordWithBLOBs>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        HashMap<String,Object> map = new HashMap();
        map.put("pageParams", pageParams);
        map.put("staffName",staffName);
        try{
            List<EduTrainingRecordWithBLOBs> list=eduTrainingRecordMapper.getByStaffName(map);
            if(list.size()>0){
                for(EduTrainingRecordWithBLOBs record:list){
                    if(record.getStaffUserId()!=null){
                        String[] str=record.getStaffUserId().split(",");
                        StringBuffer names=new StringBuffer();
                        for(int i=0;i<str.length;i++){
                            names.append(usersMapper.getUsernameByUserId(str[i])+","); //根据 id 找名字
                        }
                        record.setStaffUserId(names.toString());
                    }
                }
                json.setObj(list);
            }
            json.setTotleNum(eduTrainingRecordMapper.getByStaffNameCount(staffName));
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    public List<EduTrainingRecordWithBLOBs> getHrStaffContractList(String userId){

        //查询所有数据
        List<EduTrainingRecordWithBLOBs> all = eduTrainingRecordMapper.getHrStaffContractList(userId);

        for(EduTrainingRecordWithBLOBs eduTrainingRecordWithBLOBs:all){
            StringBuffer sb =new StringBuffer();
            if(eduTrainingRecordWithBLOBs.getStaffUserId()!=null){
                String staffUserId = eduTrainingRecordWithBLOBs.getStaffUserId();
                String[] split = staffUserId.split(",");
                for(String s:split){
                    Users byuserId = usersMapper.getUserId(s);
                    if(byuserId!=null){
                        sb.append(byuserId.getUserName()+",");
                    }
                }
            }
            eduTrainingRecordWithBLOBs.setStaffUserName(sb.toString());
        }
        return all;
    }
}
